﻿using System;
using System.Collections.Generic;
using System.Linq;
using WJ.Infrastructure.Util;

namespace WJ.Infrastructure.WeChat
{
    public class Sign
    {
        public static string Create(object obj, string signFieldName = "sign")
        {
            var type = obj.GetType();
            var properties = type.GetProperties();

            SortedDictionary<string, string> dic = new SortedDictionary<string, string>();

            foreach (var property in properties)
            {
                string name = property.Name;

                object valueObj = property.GetValue(obj, null);

                if (valueObj == null)
                {
                    continue;
                }

                string value = valueObj.ToString();

                if (!string.IsNullOrEmpty(value) && name != signFieldName)
                {
                    dic[name] = value;
                }
            }

            string sign = "";

            foreach (var item in dic)
            {
                sign += item.Key + "=" + item.Value + "&";
            }

            sign += "key=" + Config.MchKey;

            sign = Security.GetMd5Hash(sign).ToUpper();

            return sign;
        }

    }
}